package com.yum.framework.security.service.impl;

import com.yum.common.utils.Utils;
import com.yum.system.entity.SysUser;
import com.yum.system.service.SysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Package: com.yum.system.service.impl
 * Description： TODO
 * Author: Forest
 * Date: Created in 2021/3/28 13:57
 * Version: 0.0.1
 * Modified By: duforest
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        List<SysUser> sysUsers = sysUserService.selectUserList(sysUser);
        if (!Utils.isEmpty(sysUsers)) {
            SysUser usr = sysUsers.get(0);
            List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
            return new User(usr.getUserName(), new BCryptPasswordEncoder().encode(usr.getPassWord()), auths);
        } else {
            throw new UsernameNotFoundException("当前用户不存在！");
        }

    }
}
